import router from '../../router'
import store from '../../store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
import { Message } from 'element-ui'
import { setToken, setUserNum } from '@/common/utils/auth'
import request from '@/common/utils/request'
import SSO from '@/message/login/sso'
import SSO1 from '@/message/login/sso1'
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (Object.keys(to.query).length === 0) {
    next()
  } else {
    SSOLogin(to.query, next)
  }
  NProgress.done()
})

/**
 * @package SSO登录上送数据
 * @param val: URL参数
 * @param next: router设置项
 */
function SSOLogin(val, next) {
  const resBody = new SSO1()
  resBody.data.serverip = val.serverip
  resBody.data.socketport = val.socketport
  resBody.data.ticket = val.ticket
  request(resBody)
    .then(response => {
      if (response.SYS_HEAD.ReturnCode === '000000') {
        const userInfo = response.RspInfo
        store.dispatch('Login1', userInfo)
        SSOLogin1(userInfo, next)
      } else {
        Message.error(response.ReturnMessage || '登录失败')
      }
    })
}
function SSOLogin1(userInfo, next) {
  const resBody1 = new SSO()
  resBody1.data.MenuViewNum = '010'
  // eslint-disable-next-line no-undef
  request(resBody1)
    .then(response => {
      if (response.SYS_HEAD.ReturnCode === '000000') {
        const data = response.SYS_HEAD
        // next({ path: '/' })
        setToken('Admin-Token')
        setUserNum(userInfo.userid)
        store.dispatch('SSOLogin', userInfo)
        store.dispatch('GetMenu', data)
        next({ path: '/' })
        Message.success(response.ReturnMessage || '登录成功')
      } else {
        Message.error(response.ReturnMessage || '登录失败')
        next({ path: '/' })
      }
    })
}
export default SSOLogin

